package com.example.fw;

public class ContactHelper extends HelpersBase{

	public ContactHelper(ApplicationManager applicationManager) {
		super(applicationManager);
	}

	private  int timeout = Integer.valueOf(manager.getProperty("timeout"));
			
	public void createContact(Contact contact) {
		initContactCreation();
		fillContactForm(contact);
		confirmContactCreation();		
	}
	
	public void deleteFirstContact(){
		selectFirstContact();
		submitContactDeletion();
	}
	
	public void deleteContactCreated(){
		submitContactDeletion();
	}
	
	public Contact getFirstContact() {
		selectFirstContact();
			manager.getAutoItHelper()
			.click("Edit")
			.winWaitAndActivate("Update Contact", "", timeout);
		Contact contact = new Contact()
			.setFirstname(manager.getAutoItHelper().getText("TDBEdit12"))
			.setLastName(manager.getAutoItHelper().getText("TDBEdit11"));
		manager.getAutoItHelper()
			.click("Cancel")
			.winWaitAndActivate("AddressBook Portable", "", timeout);
		return contact;	
	}
	
	public void searchContactByLastname(String lastname){
		manager.getAutoItHelper()
		.winWaitAndActivate("AddressBook Portable", "", timeout)
		.send("TEdit1", lastname)
		.click("TRbButton10");		
	}
	
	public void selectContactCreated(){
		// Фокус на нужной строке
		for (int i = 0; i <= Integer.valueOf(getIndex()); i++) {
			manager.getAutoItHelper()
			.winWaitAndActivate("AddressBook Portable", "", timeout)
			.focus("TListView1")
			.send("{DOWN}");
		}
		// Нажимаем пробел, чтобы выделить
		manager.getAutoItHelper()
		.winWaitAndActivate("AddressBook Portable", "", timeout)
		.send("{SPACE}");
	}

	private String getIndex() {
		return manager.getAutoItHelper().getTLietViewSelected("TListView1");
	}
	
	private void selectFirstContact() {
		manager.getAutoItHelper()
			.winWaitAndActivate("AddressBook Portable", "", timeout)
			.focus("TListView1")
			.send("{DOWN}{SPACE}");
	}

	private void initContactCreation() {
		manager.getAutoItHelper()
			.winWaitAndActivate("AddressBook Portable", "", timeout)
			.click("Add")
			.winWaitAndActivate("Add Contact", "", timeout);
	}

	private void fillContactForm(Contact contact) {
		manager.getAutoItHelper()
			.send("TDBEdit12", contact.firsname)
			.send("TDBEdit11", contact.lastname);
	}
	
	private void confirmContactCreation() {
		manager.getAutoItHelper().click("Save")
			.winWaitAndActivate("AddressBook Portable", "", timeout);
	}
	
	private void submitContactDeletion() {
		manager.getAutoItHelper()
			.click("Delete")
			.winWaitAndActivate("Confirm", "", timeout)
			.click("TButton2");
	}

}
